<?php


namespace app\controller\wmapi\message;

use support\Request;
use support\Response;
use Tinywan\Validate\Validate;
use app\controller\wmapi\IndexController;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use DingTalk\Crypto\DingTalkEncryptor;
use support\Log;

class MessageNotifyController
{

    /**
     * 消息通知测试接口
     * @param Request $request
     * @return Response
     */
    public function dingDingNotifyTest(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        $appKey = $param['appKey'];
        $appSecret = $param['appSecret'];
//        $appKey = "dingzsmqvdklv4edbj8k";
//        $appSecret = "02H0PNxxIhXBKDiuEgXsHRd-ZQSwB8hGdZY0OlYJMGpB9IIp7lJvlUYQWMBylT6C";

        $CorpId = "ding700568a8a08c628d24f2f5cc6abecb85";


        $url = "https://oapi.dingtalk.com/gettoken?appkey=" . $appKey . "&appsecret=" . $appSecret;
//        $url = "https://oapi.dingtalk.com/gettoken?corpid= . $CorpId . &corpsecret=". $appSecret;


//        $url = "https://oapi.dingtalk.com/gettoken?appkey=" . urlencode($appKey) . "&appsecret=" . urlencode($appSecret);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $response = curl_exec($ch);
        curl_close($ch);

        $responseArray = json_decode($response, true);
        IndexController::logError('dingDingNotifyTest-1', $responseArray['errmsg'], $adminId, '');

        if (isset($responseArray['errcode']) && $responseArray['errcode'] != 0) {
            // 处理错误
            echo 'Error: ' . $responseArray['errmsg'];
            IndexController::logError('dingDingNotifyTest-2', $responseArray['errmsg'], $adminId, '');
        } else {
            // 处理成功响应
            echo 'AccessToken: ' . $responseArray['access_token'];
            IndexController::logError('dingDingNotifyTest-3', $responseArray['access_token'], $adminId, '');
        }

        $access_token = $responseArray["access_token"];
        $mobile = $param['mobile'];
        // 使用access_token获取用户信息
        $userInfo = self::getUserInfoByCode($access_token, $mobile);

        $data = [
            'response' => $responseArray,
            'userInfo' => $userInfo,
        ];

        return IndexController::successed(json_encode($data), '获取登入信息');


    }


    /**
     * 钉钉 - 消息通知机器人
     * @param Request $request
     * @return Response
     */
    public function dingDingNotifyTest2(Request $request)
    {


        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $agent_id = 3493960884;

//        $appKey = $param['appKey'];
//        $appSecret = $param['appSecret'];
        $appKey = "dingzsmqvdklv4edbj8k";
        $appSecret = "02H0PNxxIhXBKDiuEgXsHRd-ZQSwB8hGdZY0OlYJMGpB9IIp7lJvlUYQWMBylT6C";
        $url = "https://oapi.dingtalk.com/gettoken?appkey=" . $appKey . "&appsecret=" . $appSecret;
//        $CorpId = "ding700568a8a08c628d24f2f5cc6abecb85";
//        $url = "https://oapi.dingtalk.com/gettoken?corpid= . $CorpId . &corpsecret=". $appSecret;
//        $url = "https://oapi.dingtalk.com/gettoken?appkey=" . urlencode($appKey) . "&appsecret=" . urlencode($appSecret);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $response = curl_exec($ch);
        curl_close($ch);

        $responseArray = json_decode($response, true);

        if (isset($responseArray['errcode']) && $responseArray['errcode'] != 0) {
            // 处理错误
            echo 'Error: ' . $responseArray['errmsg'];
            IndexController::logError('dingDingNotifyTest2', $responseArray['errmsg'], $adminId, '');
        } else {
            // 处理成功响应
            echo 'AccessToken: ' . $responseArray['access_token'];
            IndexController::logError('dingDingNotifyTest2', $responseArray['access_token'], $adminId, '');
        }

        $access_token = $responseArray["access_token"];

        $mobile = $param['mobile'];
        // 使用access_token获取用户信息
        $userInfo = self::getUserInfoByCode($access_token, $mobile);
        $userid = $userInfo['result']['userid'];


        $access_token = $responseArray['access_token'];
        $title = $param['title'];
        $markdown = $param['markdown'];
        $single_url = $param['single_url'];

        //构造请求的消息体
        $url = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=" . $access_token;
//        $message = [
//            "agent_id" => $param['agent_id'],
//            "userid_list" => $param['userid_list'],
//            "msg" => [
//                "msgtype" => "text",
//                "text" => [
//                    "content" => $content
//                ],
//                "safe" => 0
//            ]
//        ];

        // 使用工作通知发送消息
        $message = [
            "agent_id" => $agent_id,
            "userid_list" => $userid,
            "msg" => [
                "msgtype" => "action_card",
                "action_card" => [
                    "title" => $title,
                    "markdown" => $markdown,
                    "single_title" => '查看详情',
                    "single_url" => $single_url
                ],

                "safe" => 0
            ]
        ];

//        if ($param['message_type'] == 2){
//            // 使用消息模板发送消息
//            $message = [
//                "agent_id" => $agent_id,
//                "userid_list" => $userid,
//                "template_id" => "e27a9eed42b34a14a2xxxx",
//                "data" => [
//                    "title" => $title,
//                    "markdown" => $markdown,
//                    "single_title" => '查看详情',
//                    "single_url" => $single_url,
//                    "safe" => 0
//                ]
//            ];
//            $url = "https://oapi.dingtalk.com/topapi/message/corpconversation/sendbytemplate?access_token=" . $access_token;
//
//        }

        //发送HTTP请求




        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        IndexController::logSuccessed('dingDingNotifyTest2-7', json_encode($message), $adminId, '');

        $result = curl_exec($ch);
        curl_close($ch);
        $json_result = json_decode($result, true);
        IndexController::logSuccessed('dingDingNotifyTest2-4', $json_result, $adminId, '');
        if ($json_result["errcode"] == 0) {
            echo "消息发送成功!";
        } else {
            echo "消息发送失败!";
            IndexController::logError('dingDingNotifyTest2-5', $json_result['errcode'], $adminId, '');

        }
        $data = [
//            'response' => $responseArray,
//            'userInfo' => $userInfo,
            'result' => $json_result,
        ];


        return IndexController::successed(json_encode($data), '钉钉通知');

    }


    public static function getUserInfoByCode($accessToken, $mobile)
    {

//        $url = "https://oapi.dingtalk.com/topapi/v2/user/get?access_token={$accessToken}";
//        $url =  "https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token={$accessToken}";
        $url = "https://oapi.dingtalk.com/topapi/v2/user/getbymobile?access_token={$accessToken}&mobile={$mobile}";
//        $url = "https://oapi.dingtalk.com/sns/getuserinfo_bycode?access_token={$accessToken}&code={$code}";
        $response = file_get_contents($url);
        return json_decode($response, true);
    }




    /**
     * 钉钉 - 消息通知机器人
     * @param Request $request
     * @return Response
     */
    public static function dingDingWorkNotify($data,$adminId)
    {




        $agent_id = 3493960884;
        $appKey = "dingzsmqvdklv4edbj8k";
        $appSecret = "02H0PNxxIhXBKDiuEgXsHRd-ZQSwB8hGdZY0OlYJMGpB9IIp7lJvlUYQWMBylT6C";
        $url = "https://oapi.dingtalk.com/gettoken?appkey=" . $appKey . "&appsecret=" . $appSecret;
//        $CorpId = "ding700568a8a08c628d24f2f5cc6abecb85";
//        $url = "https://oapi.dingtalk.com/gettoken?corpid= . $CorpId . &corpsecret=". $appSecret;
//        $url = "https://oapi.dingtalk.com/gettoken?appkey=" . urlencode($appKey) . "&appsecret=" . urlencode($appSecret);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $response = curl_exec($ch);
        curl_close($ch);

        $responseArray = json_decode($response, true);

        if (isset($responseArray['errcode']) && $responseArray['errcode'] != 0) {
            // 处理错误
            echo 'Error: ' . $responseArray['errmsg'];
            IndexController::logError('dingDingWorkNotify', $responseArray['errmsg'], $adminId, '');
        } else {
            // 处理成功响应
            echo 'AccessToken: ' . $responseArray['access_token'];
            IndexController::logSuccessed('dingDingWorkNotify', $responseArray['access_token'], $adminId, '');
        }

        $access_token = $responseArray["access_token"];
//        $data = [
//            'mobile' => '',
//            'title' => '',
//            'markdown' => '',
//            'single_url' => '',
//        ];
        $mobile = $data['mobile'];
        // 使用access_token获取用户信息
        $userInfo = self::getUserInfoByCode($access_token, $mobile);
        $userid = $userInfo['result']['userid'];


        $access_token = $responseArray['access_token'];
        $title = $data['title'];
        $markdown = $data['markdown'];
//        $single_url = $data['single_url'];
//        $single_url = 'http://frontforeign.olivenev.com/#/login';
        $single_url = 'http://frontforeign.olivenev.com/#/dashboard';

        //构造请求的消息体
        $url = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=" . $access_token;
//        $message = [
//            "agent_id" => $param['agent_id'],
//            "userid_list" => $param['userid_list'],
//            "msg" => [
//                "msgtype" => "text",
//                "text" => [
//                    "content" => $content
//                ],
//                "safe" => 0
//            ]
//        ];

        // 使用工作通知发送消息
        $message = [
            "agent_id" => $agent_id,
            "userid_list" => $userid,
            "msg" => [
                "msgtype" => "action_card",
                "action_card" => [
                    "title" => $title,
                    "markdown" => $markdown,
                    "single_title" => '查看详情',
                    "single_url" => $single_url
                ],

                "safe" => 0
            ]
        ];

//        if ($param['message_type'] == 2){
//            // 使用消息模板发送消息
//            $message = [
//                "agent_id" => $agent_id,
//                "userid_list" => $userid,
//                "template_id" => "e27a9eed42b34a14a2xxxx",
//                "data" => [
//                    "title" => $title,
//                    "markdown" => $markdown,
//                    "single_title" => '查看详情',
//                    "single_url" => $single_url,
//                    "safe" => 0
//                ]
//            ];
//            $url = "https://oapi.dingtalk.com/topapi/message/corpconversation/sendbytemplate?access_token=" . $access_token;
//
//        }

        //发送HTTP请求




        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        IndexController::logSuccessed('dingDingWorkNotify', json_encode($message), $adminId, '');

        $result = curl_exec($ch);
        curl_close($ch);
        $json_result = json_decode($result, true);
        IndexController::logSuccessed('dingDingWorkNotify', $json_result, $adminId, '');
        if ($json_result["errcode"] == 0) {
            echo "消息发送成功!";
        } else {
            echo "消息发送失败!";
            IndexController::logError('dingDingWorkNotify', $json_result['errcode'], $adminId, '');

        }
        $data = [
//            'response' => $responseArray,
//            'userInfo' => $userInfo,
            'result' => $json_result,
        ];
        return $data;
//        return IndexController::successed(json_encode($data), '钉钉通知');

    }



    /**
     * 回调地址
     * @param Request $request
     */
    public function dingTalkMessageNotification(Request $request)
    {

    }







    // Webhook入口方法
    public function dingTalkMessageWebhook(Request $request)
    {
// 引入client
        $client = new \GuzzleHttp\Client();

        $data = [
            'msgtype' => 'link',
            'link' => [
                'text' => '内容',
                'title' => '标题',
                'picUrl' => '图片URL,可不填写',
                'messageUrl' => "需要跳转的url地址"
            ]
        ];

        $res = $client->post("https://oapi.dingtalk.com/robot/send?access_token=f7d4d868f88fb7d40c9b675739a2e3523d0c1d6ecbe4c4d045ad9c89674d4960",[
            'headers' => [
                'content-type' => 'application/json'
            ],
            'body' => json_encode($data),
        ]);
        return $res;
    }
















}
